<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="130px" v-loading="formLoading">
      <el-tabs>
        <el-tab-pane label="基本信息">
          <el-form-item label="用户名" prop="userId">
            <el-input v-model="formData.userId" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="企业名称" prop="companyName">
            <el-input v-model="formData.companyName" placeholder="请输入企业名称" />
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="socialCreditCode">
            <el-input v-model="formData.socialCreditCode" placeholder="请输入统一社会信用代码" />
          </el-form-item>
          <!-- 营业执照到期日期 -->
          <el-form-item label="营业执照到期日期" prop="businessLicenseExpireDate">
            <!-- <el-input v-model="formData.businessLicenseExpireDate" placeholder="请输入营业执照到期日期" /> -->
            <!-- {{ value1 }} -->
            <!-- {{ formData.businessLicenseExpireDate }} -->
            <!-- {{ businessLicenseExpireDateCom }} -->
            <el-date-picker v-model="value1" type="date" placeholder="请选择营业执照到期日期" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" style="width: 100%"/>
          </el-form-item>
          <!-- 注册地址 -->
          <el-form-item label="注册地址" prop="registrationAddress">
            <el-input v-model="formData.registrationAddress" placeholder="请输入注册地址" />
          </el-form-item>
          <!-- 开户行 -->
          <el-form-item label="开户行" prop="bankName">
            <el-input v-model="formData.bankName" placeholder="请输入开户行" />
          </el-form-item>
          <!-- 分行 -->
          <el-form-item label="分行" prop="bankBranch">
            <el-input v-model="formData.bankBranch" placeholder="请输入分行" />
          </el-form-item>
          <!-- 银行卡号 -->
          <el-form-item label="银行卡号" prop="bankAccountNumber">
            <el-input v-model="formData.bankAccountNumber" placeholder="请输入银行卡号" />
          </el-form-item>

          <!-- 企业认证特有信息 -->
          <!-- <template v-if="formData.authType === 2">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
            </el-form-item>
            <el-form-item label="职位" prop="position">
              <el-input v-model="formData.position" placeholder="请输入职位" />
            </el-form-item>
          </template> -->

          <!-- 状态信息 -->
          <el-divider>认证状态</el-divider>
          <el-form-item label="认证状态" prop="verificationStatus">
            <el-radio-group v-model="formData.verificationStatus">
              <el-radio :label="1">待审核</el-radio>
              <el-radio :label="2">已认证</el-radio>
              <el-radio :label="3">未通过</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="审核备注" prop="auditRemark">
            <el-input v-model="formData.auditRemark" type="textarea" :rows="3" placeholder="请输入审核备注" />
          </el-form-item>
          <!--           
          <el-form-item label="认证通过时间" prop="authTime" v-if="formData.verificationStatus === 1">
            <el-date-picker
              v-model="formData.authTime"
              type="datetime"
              value-format="x"
              placeholder="选择认证通过时间"
            />
          </el-form-item> -->
        </el-tab-pane>
        <el-tab-pane label="联系人信息">
          <!-- 联系人姓名 -->
          <el-form-item label="联系人姓名" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入联系人姓名" />
          </el-form-item>
          <!-- 联系人手机号码 -->
          <el-form-item label="联系人手机号码" prop="contactMobile">
            <el-input v-model="formData.contactMobile" placeholder="请输入手机号码" />
          </el-form-item>
          <!-- 联系人邮箱 -->
          <el-form-item label="联系人邮箱" prop="contactEmail">
            <el-input v-model="formData.contactEmail" placeholder="请输入邮箱" />
          </el-form-item>
          <!-- 办公地址 -->
          <el-form-item label="办公地址" prop="officeAddress">
            <el-input v-model="formData.officeAddress" placeholder="请输入办公地址" />
          </el-form-item>
          <!-- 详细地址 -->
          <el-form-item label="详细地址" prop="detailedAddress">
            <el-input v-model="formData.detailedAddress" placeholder="请输入详细地址" />
          </el-form-item>
          <el-divider>合同</el-divider>
          <!-- 合同PDF URL -->
          <el-form-item label="合同PDF URL" prop="contractPdfUrl">
            <el-button type="primary" @click="viewContractDetails(formData.contractPdfUrl)">查看合同详情</el-button>
          </el-form-item>
          <!-- 合同编号 -->
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="formData.contractNumber" placeholder="请输入合同编号" />
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="证件信息">
          <div class="grid grid-cols-1 gap-4">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <div class="mb-2 font-bold">法人身份证正面URL</div>
                <el-form-item prop="legalPersonIdCardFront">
                  <el-input v-model="formData.legalPersonIdCardFront" placeholder="请输入法人身份证正面URL">
                    <template #append>
                      <el-button @click="previewImage(formData.legalPersonIdCardFront)">预览</el-button>
                    </template>
                  </el-input>
                  <el-image v-if="formData.legalPersonIdCardFront" :src="formData.legalPersonIdCardFront"
                    :preview-src-list="[formData.legalPersonIdCardFront]" fit="contain"
                    style="width: 100%; max-height: 150px; margin-top: 8px;" />
                </el-form-item>
              </div>
              <div>
                <div class="mb-2 font-bold">法人身份证反面URL</div>
                <el-form-item prop="legalPersonIdCardBack">
                  <el-input v-model="formData.legalPersonIdCardBack" placeholder="请输入身份证背面URL">
                    <template #append>
                      <el-button @click="previewImage(formData.legalPersonIdCardBack)">预览</el-button>
                    </template>
                  </el-input>
                  <el-image v-if="formData.legalPersonIdCardBack" :src="formData.legalPersonIdCardBack"
                    :preview-src-list="[formData.legalPersonIdCardBack]" fit="contain"
                    style="width: 100%; max-height: 150px; margin-top: 8px;" />
                </el-form-item>
              </div>
            </div>
            <!-- 联系人身份证正面URL -->
            <div class="grid grid-cols-2 gap-4">
              <div>
                <div class="mb-2 font-bold">联系人身份证正面URL</div>
                <el-form-item prop="contactIdCardFront">
                  <el-input v-model="formData.contactIdCardFront" placeholder="联系人身份证正面URL">
                    <template #append>
                      <el-button @click="previewImage(formData.contactIdCardFront)">预览</el-button>
                    </template>
                  </el-input>
                  <el-image v-if="formData.contactIdCardFront" :src="formData.contactIdCardFront"
                    :preview-src-list="[formData.contactIdCardFront]" fit="contain"
                    style="width: 100%; max-height: 150px; margin-top: 8px;" />
                </el-form-item>
              </div>
              <div>
                <div class="mb-2 font-bold">联系人身份证反面URL</div>
                <el-form-item prop="contactIdCardBack">
                  <el-input v-model="formData.contactIdCardBack" placeholder="请输入身份证背面URL">
                    <template #append>
                      <el-button @click="previewImage(formData.contactIdCardBack)">预览</el-button>
                    </template>
                  </el-input>
                  <el-image v-if="formData.contactIdCardBack" :src="formData.contactIdCardBack"
                    :preview-src-list="[formData.contactIdCardBack]" fit="contain"
                    style="width: 100%; max-height: 150px; margin-top: 8px;" />
                </el-form-item>
              </div>
            </div>
            <!-- 营业执照URL -->
            <div class="grid grid-cols-2 gap-4">
              <div>
                <div class="mb-2 font-bold">营业执照URL
                </div>
                <el-form-item prop="businessLicenseUrl">
                  <el-input v-model="formData.businessLicenseUrl" placeholder="请输入法人身份证正面URL">
                    <template #append>
                      <el-button @click="previewImage(formData.businessLicenseUrl)">预览</el-button>
                    </template>
                  </el-input>
                  <el-image v-if="formData.businessLicenseUrl" :src="formData.businessLicenseUrl"
                    :preview-src-list="[formData.businessLicenseUrl]" fit="contain"
                    style="width: 100%; max-height: 150px; margin-top: 8px;" />
                </el-form-item>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">确定</el-button>
    </template>
  </Dialog>

  <!-- 图片预览器 -->
  <el-image-viewer v-if="imageViewerVisible" @close="imageViewerVisible = false" :url-list="previewImages"
    :initial-index="previewIndex" />
</template>

<script setup lang="ts">
import { ref, reactive, computed, unref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { AccountAuthApi, type AccountAuthVO } from '@/api/weiyi/accountauth'
import { useMessage } from '@/hooks/web/useMessage'

const emit = defineEmits(['success'])
const message = useMessage() // 消息提示

// 表单相关
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const formLoading = ref(false)
const formType = ref('') // create 或 update
const formData = ref<Partial<AccountAuthVO>>({
  id: undefined,
  username: '',
  realName: '',
  idCard: '',
  phoneNumber: '',
  email: '',
  companyName: '',
  position: '',
  idCardFront: '',
  idCardBack: '',
  verificationStatus: 0,
  authType: 1,
  auditRemark: '',
  authTime: undefined
})
const value1 = ref('2025-06-06')

// 图片预览相关
const imageViewerVisible = ref(false)
const previewImages = ref<string[]>([])
const previewIndex = ref(0)

// 预览图片
const previewImage = (url: string) => {
  if (!url) {
    message.warning('请先输入图片URL')
    return
  }
  previewImages.value = [url]
  previewIndex.value = 0
  imageViewerVisible.value = true
}

// 表单标题
const dialogTitle = computed(() => {
  return formType.value === 'create' ? '新增账户认证' : '编辑账户认证'
})
// 营业执照到期时间
// const businessLicenseExpireDateCom = computed(() => {
//   return formData.value.businessLicenseExpireDate
//     ? new Date(formData.value.businessLicenseExpireDate).toLocaleDateString()
//     : ''
// })
// 处理营业执照到期日期
const handleBusinessLicenseExpireDate = (dateArray: [number, number, number]) => {
  const [year, month, day] = dateArray;
  const date = new Date(year, month - 1, day);
  // 使用 Intl 格式化（兼容性较好）
  const formattedDate = new Intl.DateTimeFormat('en-CA', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).format(date).replace(/\//g, '-');
  return formattedDate
}

// 表单校验规则
const formRules = reactive<FormRules>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入正确的身份证号码',
      trigger: 'blur'
    }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ],
  email: [
    {
      pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ],
  authType: [{ required: true, message: '请选择认证类型', trigger: 'change' }],
  companyName: [
    {
      required: true,
      message: '请输入公司名称',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (formData.value.authType === 2 && (!value || value.trim() === '')) {
          callback(new Error('请输入公司名称'))
        } else {
          callback()
        }
      }
    }
  ],
  idCardFront: [{ required: true, message: '请输入身份证正面URL', trigger: 'blur' }],
  idCardBack: [{ required: true, message: '请输入身份证背面URL', trigger: 'blur' }]
})

// 打开表单
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  formType.value = type
  resetForm()

  // 如果是编辑模式，需要获取详情
  if (type === 'update' && id) {
    try {
      formLoading.value = true
      const data = await AccountAuthApi.getAccountAuth(id)
      console.log('datagetAccountAuth', data);

      formData.value = data
      formData.value.businessLicenseExpireDate = data.businessLicenseExpireDate
        ? handleBusinessLicenseExpireDate(data.businessLicenseExpireDate)
        : ''
    } catch (error) {
      console.error('获取详情失败:', error)
      message.error('获取详情失败')
      dialogVisible.value = false
    } finally {
      formLoading.value = false
    }
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    id: undefined,
    username: '',
    realName: '',
    idCard: '',
    phoneNumber: '',
    email: '',
    companyName: '',
    position: '',
    idCardFront: '',
    idCardBack: '',
    verificationStatus: 0,
    authType: 1,
    auditRemark: '',
    authTime: undefined
  }

  formRef.value?.resetFields()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    formLoading.value = true
    if (formType.value === 'create') {
      await AccountAuthApi.createAccountAuth(formData.value as AccountAuthVO)
      message.success('新增成功')
    } else {
      await AccountAuthApi.updateAccountAuth(formData.value as AccountAuthVO)
      message.success('修改成功')
    }

    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error !== 'cancel') {
      message.error('表单提交失败')
    }
  } finally {
    formLoading.value = false
  }
}
// 查看合同详情的逻辑
const viewContractDetails = (contractPdfUrl) => {
  window.open(contractPdfUrl, "_blank");
}

// 导出方法供父组件调用
defineExpose({
  open
})

</script>

<style lang="scss" scoped>
.cursor-pointer {
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: scale(1.05);
  }
}
</style>